package android.fwirk;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.jplurk.DateTime;
import com.google.jplurk.Qualifier;

import twitter4j.GeoLocation;
import twitter4j.Paging;
import twitter4j.Status;
import twitter4j.TwitterException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.fwirk.facebook.FacebookStatus;
import android.fwirk.facebook.FacebookUser;
import android.fwirk.obj.CustomLocationListener;
import android.fwirk.obj.CustomProgressDialog;
import android.fwirk.obj.StatusMessage;
import android.fwirk.obj.StatusMessageAdapter;
import android.fwirk.plurk.Plurk;
import android.fwirk.plurk.PlurkUser;
import android.fwirk.twitter.TweetStatus;
import android.fwirk.twitter.TwitterUser;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class HomeActivity extends Activity implements OnClickListener,
		OnKeyListener {
	EditText statusText;
	ImageView facebookImg;
	ImageView twitterImg;
	ImageView plurkImg;
	ImageView happyImg;
	ImageView angryImg;
	ImageView dizzyImg;
	ImageView grinImg;
	ImageView inloveImg;
	ImageView sleepImg;
	ImageView xgrinImg;
	ImageView cryImg;
	ImageView meawImg;
	ImageView sweatImg;
	ImageView deadImg;
	ImageView bigeyesImg;
	Button sendButton;
	TextView statusLen;
	StatusMessageAdapter smAdapter;
	boolean canFacebook;
	boolean canTwitter;
	boolean canPlurk;
	CustomProgressDialog progress;
	int tID = 0;
	StatusMessage empty;
	boolean tweeted;
	boolean plurked;
	boolean facebookStatused;
	ImageButton pictureButton;
	ImageButton geoButton;
	Intent intent;
	final static int MENU_LOGOUT = 0;
	final int DIALOG_PROGRESS = 0;
	final int DIALOG_SIGNOUT = 1;
	final int DIALOG_PICTURE = 2;
	final int ACTIVITY_GALLERY=0;
	final int ACTIVITY_CAMERA=1;
	LocationManager lm;
	AlertDialog signoutDialog;
	AlertDialog pictureDialog;
	CustomLocationListener ll;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		tID = 0;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home);
		Bundle b = getIntent().getExtras();
		canFacebook = false;
		canTwitter = false;
		canPlurk = false;
		if (b != null) {
			canFacebook = b.getBoolean("canFacebook", false);
			canTwitter = b.getBoolean("canTwitter", false);
			canPlurk = b.getBoolean("canPlurk", false);
		}
		statusText = (EditText) findViewById(R.id.statusmsg);
		statusLen = (TextView) findViewById(R.id.statusLen);
		statusLen.setText("Left: 140");
		facebookImg = (ImageView) findViewById(R.id.efacebook);
		twitterImg = (ImageView) findViewById(R.id.etwitter);
		plurkImg = (ImageView) findViewById(R.id.eplurk);
		happyImg = (ImageView) findViewById(R.id.happyImg);
		grinImg = (ImageView) findViewById(R.id.grinImg);
		cryImg = (ImageView) findViewById(R.id.cryImg);
		xgrinImg = (ImageView) findViewById(R.id.xgrinImg);
		deadImg = (ImageView) findViewById(R.id.deadImg);
		bigeyesImg = (ImageView) findViewById(R.id.bigeyesImg);
		sleepImg = (ImageView) findViewById(R.id.sleepImg);
		inloveImg = (ImageView) findViewById(R.id.inloveImg);
		meawImg = (ImageView) findViewById(R.id.meawImg);
		dizzyImg = (ImageView) findViewById(R.id.dizzyImg);
		angryImg = (ImageView) findViewById(R.id.angryImg);
		sweatImg = (ImageView) findViewById(R.id.sweatImg);
		happyImg .setOnClickListener(this);
		grinImg .setOnClickListener(this);
		cryImg.setOnClickListener(this);
		xgrinImg .setOnClickListener(this);
		deadImg.setOnClickListener(this);
		bigeyesImg .setOnClickListener(this);
		sleepImg .setOnClickListener(this);
		inloveImg.setOnClickListener(this);
		meawImg .setOnClickListener(this);
		dizzyImg.setOnClickListener(this);
		angryImg.setOnClickListener(this);
		sweatImg .setOnClickListener(this);
		pictureButton = (ImageButton) findViewById(R.id.pictureb);
		pictureButton.setOnClickListener(this);
		geoButton = (ImageButton) findViewById(R.id.geotagb);
		geoButton.setOnClickListener(this);
		facebookImg.setVisibility(View.GONE);
		twitterImg.setVisibility(View.GONE);
		plurkImg.setVisibility(View.GONE);
		sendButton = (Button) findViewById(R.id.sendb);
		progress = new CustomProgressDialog(this);
		statusText.setOnKeyListener(this);
		progress.setText("Retrieving recent status...");
		progress.setImage1(R.drawable.facebookd);
		progress.setImage2(R.drawable.twitterd);
		progress.setImage3(R.drawable.plurkd);
		progress.setImage1Visibility(View.GONE);
		progress.setImage2Visibility(View.GONE);
		progress.setImage3Visibility(View.GONE);
		Builder bd = new Builder(this);
		signoutDialog = bd.setMessage("Sign out?").setPositiveButton("Yes",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						if (which == DialogInterface.BUTTON_POSITIVE) {
							showDialog(DIALOG_PROGRESS);
							new LogoutThread(logoutH, tID).start();
						}

					}
				}).setNegativeButton("No",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						if (which == DialogInterface.BUTTON_NEGATIVE) {
							dialog.dismiss();
						}

					}
				}).create();
		ll=new CustomLocationListener();
		lm=(LocationManager) getSystemService(Context.LOCATION_SERVICE);
		intent = new Intent(this, CustomDialogActivity.class);
		if (canFacebook) {
			facebookImg.setOnClickListener(this);
			facebookImg.setSelected(true);
			facebookImg.setVisibility(View.VISIBLE);
			facebookImg.setImageResource(R.drawable.facebookhead);
			progress.setImage1Visibility(View.VISIBLE);
		}
		if (canTwitter) {
			twitterImg.setOnClickListener(this);
			twitterImg.setSelected(true);
			twitterImg.setImageResource(R.drawable.twitterhead);
			twitterImg.setVisibility(View.VISIBLE);
			progress.setImage2Visibility(View.VISIBLE);
		}
		if (canPlurk) {
			plurkImg.setOnClickListener(this);
			plurkImg.setSelected(true);
			plurkImg.setImageResource(R.drawable.plurkhead);
			plurkImg.setVisibility(View.VISIBLE);
			progress.setImage3Visibility(View.VISIBLE);
		}
		sendButton.setOnClickListener(this);
		smAdapter = new StatusMessageAdapter(this, R.layout.row);
		final CharSequence[] items = {"Gallery","Camera","Cancel"};
		AlertDialog.Builder builder = new AlertDialog.Builder(this);		
		builder.setTitle("Choose Picture Source");
		builder.setItems(items, new DialogInterface.OnClickListener() {
		    public void onClick(DialogInterface dialog, int item) {
		        switch(item) {
		        	case 0:
		        		// To open up a gallery browser  
		        		Intent intent = new Intent();  
		        		intent.setType("image/*");  
		        		intent.setAction(Intent.ACTION_GET_CONTENT);  
		        		startActivityForResult(Intent.createChooser(intent, "Select Picture"),ACTIVITY_GALLERY);  
		        		break;
		        	case 1:
		        		Intent cameraIntent=new Intent(getApplicationContext(),CameraActivity.class);
		    			startActivityForResult(cameraIntent, ACTIVITY_CAMERA);
		        		break;
		        	case 2:
		        		dialog.dismiss();
		        		break;
		        }
		    }
		});
		pictureDialog=builder.create();

	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode==ACTIVITY_CAMERA) {
			if(resultCode==Activity.RESULT_OK) {
				Log.d("Test","camera return");
				if(Const.curImgData!=null) {
					tID++;
					progress.setImage1Visibility(View.GONE);
					progress.setImage2Visibility(View.GONE);
					progress.setImage3Visibility(View.GONE);
					progress.setText("Uploading image...");
					showDialog(DIALOG_PROGRESS);
					new UploadImageThread(imageH, Const.curImgData,null, tID%Integer.MAX_VALUE).start();
				}
			}
		}
		else if(requestCode==ACTIVITY_GALLERY) {
			if(resultCode==Activity.RESULT_OK) {
				String path=getRealPathFromURI(data.getData());
				Log.d("Test",path);
				File f=new File(path);
				tID++;
				progress.setImage1Visibility(View.GONE);
				progress.setImage2Visibility(View.GONE);
				progress.setImage3Visibility(View.GONE);
				progress.setText("Uploading image...");
				showDialog(DIALOG_PROGRESS);
				new UploadImageThread(imageH, null,f, tID%Integer.MAX_VALUE).start();
			}
		}
	}
	
	// And to convert the image URI to the direct file system path of the image file  
	public String getRealPathFromURI(Uri contentUri) {  
	     // can post image  
	     String [] proj={MediaStore.Images.Media.DATA};  
	     Cursor cursor = managedQuery( contentUri,  
	             proj, // Which columns to return  
	             null,       // WHERE clause; which rows to return (all rows)  
	             null,       // WHERE clause selection arguments (none)  
	             null); // Order-by clause (ascending by name)  
	     int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);  
	     cursor.moveToFirst();  
	     return cursor.getString(column_index);  
	}  
	
	@Override
	protected Dialog onCreateDialog(int id) {
		if (id == DIALOG_PROGRESS) {
			return progress.getDialog();
		} else if (id == DIALOG_SIGNOUT) {
			return signoutDialog;
		} else if( id== DIALOG_PICTURE) {
			return pictureDialog;
		}
		return super.onCreateDialog(id);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, MENU_LOGOUT, 0, "Sign out").setIcon(
				R.drawable.fwirk);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_LOGOUT:
			progress.setImage1Visibility(View.GONE);
			progress.setImage2Visibility(View.GONE);
			progress.setImage3Visibility(View.GONE);
			progress.setText("Signing off...");
			tID++;
			showDialog(DIALOG_PROGRESS);
			new LogoutThread(logoutH, tID).start();
		}
		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (progress.isShowing()) {
				removeDialog(DIALOG_PROGRESS);
			} else {
				showDialog(DIALOG_SIGNOUT);
			}
			Log.d("Test", "labas");
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	public boolean onKey(View v, int keyCode, KeyEvent event) {
		if (v == statusText) {
			statusLen.setText("Left: " + (140 - statusText.getText().length()));
		}
		return false;
	}

	public void onClick(View v) {
		String smile="";
		if (v == facebookImg) {
			if (twitterImg.isSelected() || plurkImg.isSelected()) {
				facebookImg.setSelected(!facebookImg.isSelected());
			}
		} else if (v == twitterImg) {
			if (facebookImg.isSelected() || plurkImg.isSelected()) {
				twitterImg.setSelected(!twitterImg.isSelected());
			}
		} else if (v == plurkImg) {
			if (facebookImg.isSelected() || twitterImg.isSelected()) {
				plurkImg.setSelected(!plurkImg.isSelected());
			}
		} else if(v == pictureButton) {
			showDialog(DIALOG_PICTURE);
		} else if(v== geoButton) {
			geoButton.setSelected(!geoButton.isSelected());
			if(geoButton.isSelected()) {
				Toast.makeText(this, "Status geotagged", Toast.LENGTH_SHORT).show();
			}
			else {
				Toast.makeText(this, "Status un-geotagged", Toast.LENGTH_SHORT).show();
			}
		} else if (v == sendButton) {
			if (statusText.getText().length() > 0) {
				tweeted = false;
				plurked = false;
				facebookStatused = false;
				progress.setText("Updating status...");
				progress.setImage1(R.drawable.facebookd);
				progress.setImage2(R.drawable.twitterd);
				progress.setImage3(R.drawable.plurkd);
				progress.setImage1Visibility(View.GONE);
				progress.setImage2Visibility(View.GONE);
				progress.setImage3Visibility(View.GONE);
				tID++;
				UpdateStatusThread ft = null;
				UpdateStatusThread tt = null;
				UpdateStatusThread pt = null;
				boolean geoTag=false;
				if(geoButton.isSelected()) {
					lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
					geoTag=true;
				}
				if (canFacebook && facebookImg.isSelected()) {
					progress.setImage1Visibility(View.VISIBLE);
					ft = new UpdateStatusThread(statusH,lm,ll, statusText.getText()
							.toString(),geoTag, Const.TYPE_FACEBOOK, tID
							% Integer.MAX_VALUE);
					ft.start();
				}
				if (canTwitter && twitterImg.isSelected()) {
					progress.setImage2Visibility(View.VISIBLE);
					tt = new UpdateStatusThread(statusH,lm,ll, statusText.getText()
							.toString(),geoTag, Const.TYPE_TWITTER, tID
							% Integer.MAX_VALUE);
					tt.start();
				}
				if (canPlurk && plurkImg.isSelected()) {
					progress.setImage3Visibility(View.VISIBLE);
					pt = new UpdateStatusThread(statusH,lm,ll, statusText.getText()
							.toString(),geoTag, Const.TYPE_PLURK, tID
							% Integer.MAX_VALUE);
					pt.start();
				}
				WaitThread wt = new WaitThread(waitStatusH, ft, tt, pt, tID
						% Integer.MAX_VALUE);
				showDialog(DIALOG_PROGRESS);
				wt.start();
			} else {
				Toast.makeText(this,
						"Please enter something as your status message",
						Toast.LENGTH_SHORT).show();
			}
		} else if (v == happyImg) {
			smile=":)";
			if((statusText.length()+smile.length())<=140) {
				statusText.append(smile);
				statusLen.setText("Left: " + (140 - statusText.getText().length()));
			}
		} else if (v == grinImg) {
			smile=":D";
			if((statusText.length()+smile.length())<=140) {
				statusText.append(smile);
				statusLen.setText("Left: " + (140 - statusText.getText().length()));
			}
		} else if (v == bigeyesImg) {
			smile="O_O";
			if((statusText.length()+smile.length())<=140) {
				statusText.append(smile);
				statusLen.setText("Left: " + (140 - statusText.getText().length()));
			}
		} else if (v == meawImg) {
			smile=":3";
			if((statusText.length()+smile.length())<=140) {
				statusText.append(smile);
				statusLen.setText("Left: " + (140 - statusText.getText().length()));
			}
		} else if (v == deadImg) {
			smile="x_x";
			if((statusText.length()+smile.length())<=140) {
				statusText.append(smile);
				statusLen.setText("Left: " + (140 - statusText.getText().length()));
			}
		} else if (v == sleepImg) {
			smile="z_z";
			if((statusText.length()+smile.length())<=140) {
				statusText.append(smile);
				statusLen.setText("Left: " + (140 - statusText.getText().length()));
			}
		} else if (v == dizzyImg) {
			smile="@_@";
			if((statusText.length()+smile.length())<=140) {
				statusText.append(smile);
				statusLen.setText("Left: " + (140 - statusText.getText().length()));
			}
		} else if (v == angryImg) {
			smile="X(";
			if((statusText.length()+smile.length())<=140) {
				statusText.append(smile);
				statusLen.setText("Left: " + (140 - statusText.getText().length()));
			}
		} else if (v == xgrinImg) {
			smile="XD";
			if((statusText.length()+smile.length())<=140) {
				statusText.append(smile);
				statusLen.setText("Left: " + (140 - statusText.getText().length()));
			}
		} else if (v == inloveImg) {
			smile="<3";
			if((statusText.length()+smile.length())<=140) {
				statusText.append(smile);
				statusLen.setText("Left: " + (140 - statusText.getText().length()));
			}
		} else if (v == sweatImg) {
			smile="'-_-";
			if((statusText.length()+smile.length())<=140) {
				statusText.append(smile);
				statusLen.setText("Left: " + (140 - statusText.getText().length()));
			}
		} else if (v == cryImg) {
			smile="T_T";
			if((statusText.length()+smile.length())<=140) {
				statusText.append(smile);
				statusLen.setText("Left: " + (140 - statusText.getText().length()));
			}
		}
		
	}

	final Handler statusH = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.getData().getInt("tID") == tID % Integer.MAX_VALUE) {
				if (msg.getData().getBoolean("status")
						&& msg.getData().getInt("type") == Const.TYPE_FACEBOOK) {
					facebookStatused = true;
					progress.setImage1(R.drawable.facebooke);
				} else if (msg.getData().getBoolean("status")
						&& msg.getData().getInt("type") == Const.TYPE_TWITTER) {
					tweeted = true;
					progress.setImage2(R.drawable.twittere);
				} else if (msg.getData().getBoolean("status")
						&& msg.getData().getInt("type") == Const.TYPE_PLURK) {
					plurked = true;
					progress.setImage3(R.drawable.plurke);
				}
			}
		}
	};

	final Handler waitStatusH = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.getData().getInt("tID") == tID % Integer.MAX_VALUE) {
				removeDialog(DIALOG_PROGRESS);
				if (!facebookStatused && !tweeted && !plurked) {
					Toast.makeText(getApplicationContext(),
							"Could not update status", Toast.LENGTH_LONG)
							.show();
				} else {
					statusText.setText("");
					statusLen.setText("Left: 140");
					geoButton.setSelected(false);
					String note = "";
					if (facebookStatused) {
						note = "Facebook";
					}
					if (tweeted) {
						if (facebookStatused) {
							note = note + ",";
						}
						note = note + "Twitter";
					}
					if (plurked) {
						if (facebookStatused || tweeted) {
							note = note + ",";
						}
						note = note + "Plurk";
					}
					note = note + " status updated";
					if ((facebookImg.isSelected() && !facebookStatused)
							|| (twitterImg.isSelected() && !tweeted)
							|| (plurkImg.isSelected() && !plurked)) {
						note = note + " but could not update ";
						if (facebookImg.isSelected() && !facebookStatused) {
							note = note + "Facebook ";
						}
						if (twitterImg.isSelected() && !tweeted) {
							if (facebookImg.isSelected() && !facebookStatused) {
								note = note + ",";
							}
							note = note + "Twitter";
						}
						if (plurkImg.isSelected() && !plurked) {
							if ((facebookImg.isSelected() && !facebookStatused)
									|| (twitterImg.isSelected() && !tweeted)) {
								note = note + ",";
							}
							note = note + "Plurk";
						}
						note = note + " status";
					}
					Toast.makeText(getApplicationContext(), note,
							Toast.LENGTH_SHORT).show();
				}
			}
		}
	};

	final Handler logoutH = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.getData().getInt("tID") == tID % Integer.MAX_VALUE) {
				removeDialog(DIALOG_PROGRESS);
				finish();
			}
		}
	};
	
	final Handler imageH = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.getData().getInt("tID") == tID % Integer.MAX_VALUE) {
				removeDialog(DIALOG_PROGRESS);
				if (msg.getData().getBoolean("status")) {
					String url=msg.getData().getString("url");
					String text=statusText.getText().toString();
					int length=(text.length()+url.length());
					if(length>140) {
						int cut=length-140;
						text.substring(0, text.length()-cut);
					}
					text=text+url;
					statusText.setText(text);
					Toast.makeText(getApplicationContext(), "Image uploaded", Toast.LENGTH_SHORT).show();
				}
				else {
					Toast.makeText(getApplicationContext(), "Image upload failed", Toast.LENGTH_SHORT).show();
				}
				
			}
		}
	};
}

class GetStatusThread extends Thread {
	Handler mHandler;
	boolean status;
	boolean next;
	int page;
	int count;
	int tID;
	Paging pager;
	int type;
	boolean accessInternet;
	boolean append;
	Context context;
	DateTime date;
	Date ddate;

	public GetStatusThread(Context context, Handler mHandler, int page,
			int count, Date offset, int type, boolean accessInternet,
			boolean append, int tID) {
		this.mHandler = mHandler;
		this.tID = tID;
		this.page = page;
		this.count = count;
		this.type = type;
		this.accessInternet = accessInternet;
		this.context = context;
		this.append = append;
		date = null;
		if (offset != null) {
			Calendar c = Calendar.getInstance();
			c.setTime(offset);
			date = DateTime.create(c);
		}
		ddate = offset;
	}

	@Override
	public void run() {
		status = false;
		next = false;
		if (accessInternet) {
			if (type == Const.TYPE_FACEBOOK) {
				try {
					JSONArray fstatus = null;
					List<FacebookUser> uList = null;
					Log.d("Test", "facebook status get");
					JSONObject stream = null;
					JSONArray profiles = null;
					stream = Const.facebook.getStream("0", ddate, count);
					fstatus = stream.optJSONArray("posts");
					profiles = stream.optJSONArray("profiles");
					List<FacebookStatus> sList = FacebookStatus
							.getFacebookStatuses(fstatus);
					if (sList != null) {
						uList = FacebookUser.getFacebookUsers(profiles);
						if (Const.myFacebookUsers == null) {
							Const.myFacebookUsers = uList;
							int size=Const.myFacebookUsers.size();
							for (int x=0;x<size;x++) {
								FacebookUser u=Const.myFacebookUsers.get(x);
								u.downloadPic();
							}
						} else {
							int size=uList.size();
							for (int x=0;x<size;x++) {
								FacebookUser u=uList.get(x);
								if (FacebookUser.getUser(Const.myFacebookUsers,
										u.getId()) == null) {
									u.downloadPic();
									Const.myFacebookUsers.add(u);
								}
							}
						}
						int size=sList.size();
						for (int x=0;x<size;x++) {
							FacebookStatus s=sList.get(x);
							s.setOwner(FacebookUser.getUser(
									Const.myFacebookUsers, s.getActorID()));
							if (append && Const.myFacebookStatus != null) {
								Const.myFacebookStatus.add(s);
							}
						}
					}
					if (!append || Const.myFacebookStatus == null) {
						Const.myFacebookStatus = sList;
					}
					status = true;
					Log.d("Test", "facebook status got");
					if (Const.myFacebookStatus != null) {
						if (Const.myFacebookStatus.size() == count) {
							Const.myFacebookStatus.remove(count-1);
							next = true;
							Log.d("Test", "facebook got next");
						}
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if (type == Const.TYPE_TWITTER) {
				try {
					Log.d("Test", "tweet get");
					if (!append) {
						pager = new Paging(page, count);
					} else {
						if (Const.myTweets != null) {
							if (Const.myTweets.size() > 0) {
								Status last = Const.myTweets.get(
										Const.myTweets.size() - 1).getStatus();
								pager = new Paging();
								pager.setCount(count + 1);
								pager.setMaxId(last.getId());
							}
						}
					}
					List<Status> sList = null;
					sList = Const.twitter.getHomeTimeline(pager);
					if (append) {
						sList.remove(0);
					}
					List<TweetStatus> tsList = null;
					if (sList != null) {
						if (Const.myTwitterUsers == null) {
							Const.myTwitterUsers = new LinkedList<TwitterUser>();
						}
						tsList = new LinkedList<TweetStatus>();
						int size=sList.size();
						for (int x=0;x<size;x++) {
							Status s=sList.get(x);
							TwitterUser u = TwitterUser.getUser(
									Const.myTwitterUsers, s.getUser().getId());
							if (u == null) {
								u = new TwitterUser(s.getUser());
								Const.myTwitterUsers.add(u);
							}
							TweetStatus ts = new TweetStatus(s, u);
							tsList.add(ts);
							if (append && Const.myTweets != null) {
								Const.myTweets.add(ts);
							}
						}
					}
					if (!append || Const.myTweets == null) {
						Const.myTweets = tsList;
					}
					status = true;
					Log.d("Test", "tweet got");
					if (Const.myTweets != null) {
						if (Const.myTweets.size()>0) {
							Status last = Const.myTweets.get(
									Const.myTweets.size() - 1).getStatus();
							pager = new Paging();
							pager.setCount(2);
							pager.setMaxId(last.getId());
							if (Const.twitter.getHomeTimeline(pager).size() > 1) {
								next = true;
								Log.d("Test", "tweet got next");
							}
						}
					}

				} catch (TwitterException e) {
					e.printStackTrace();
				}
			} else if (type == Const.TYPE_PLURK) {
				try {
					Log.d("Test", "plurk get");
					JSONObject plurks = null;
					plurks = Const.plurk.getPc().getPlurks(date, count, 0,
							false, false);
					JSONArray plurkArray = plurks.getJSONArray("plurks");
					JSONObject plurkUsersArray = plurks
							.getJSONObject("plurk_users");
					List<Plurk> sList = Plurk.getPlurks(plurkArray, true);
					if (sList != null) {
						List<PlurkUser> uList = PlurkUser.getUsers(context,
								plurkUsersArray);
						if (Const.myPlurkUsers == null) {
							Const.myPlurkUsers = uList;
							int size=Const.myPlurkUsers.size();
							for (int x=0;x<size;x++) {
								PlurkUser u=Const.myPlurkUsers.get(x);
								u.downloadPic();
							}
						} else {
							int size=uList.size();
							for (int x=0;x<size;x++) {
								PlurkUser u=uList.get(x);
								if (PlurkUser.getUser(Const.myPlurkUsers, u
										.getUserID()) == null) {
									u.downloadPic();
									Const.myPlurkUsers.add(u);
								}
							}
						}
						int size=sList.size();
						for (int x=0;x<size;x++) {
							Plurk s=sList.get(x);
							s.setOwner(PlurkUser.getUser(Const.myPlurkUsers, s
									.getOwnerID()));
							if (append && Const.myPlurks != null) {
								Const.myPlurks.add(s);
							}
						}
					}
					if (!append || Const.myPlurks == null) {
						Const.myPlurks = sList;
					}
					status = true;
					Log.d("Test", "plurk got");
					if (Const.myPlurks != null) {
						if (Const.myPlurks.size() == count) {
							Const.myPlurks.remove(count-1);
							next = true;
							Log.d("Test", "plurks got next");
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		} else {
			status = true;
		}
		Message m = mHandler.obtainMessage();
		Bundle b = new Bundle();
		b.putInt("type", type);
		b.putBoolean("status", status);
		b.putBoolean("hasNext", next);
		b.putInt("tID", tID);
		m.setData(b);
		mHandler.sendMessage(m);
	}
}

class UpdateStatusThread extends Thread {
	Handler mHandler;
	boolean status;
	int tID;
	String message;
	int type;
	boolean getLocation;
	LocationManager lm;
	CustomLocationListener ll;
	public UpdateStatusThread(Handler mHandler,LocationManager lm, CustomLocationListener ll, String message,boolean getLocation, int type,
			int tID) {
		this.mHandler = mHandler;
		this.message = message;
		this.tID = tID;
		this.type = type;
		this.getLocation=getLocation;
		this.lm=lm;
		this.ll=ll;
	}

	@Override
	public void run() {
		status = false;
		if (type == Const.TYPE_FACEBOOK) {
			try {
				Log.d("Test", "facebook update status");
				if (Const.facebook.setStatus(message)) {
					status = true;
					Log.d("Test", "facebook status updated");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (type == Const.TYPE_TWITTER) {
			try {
				Log.d("Test", "twitter tweet");
				if(getLocation) {
					while(!ll.hasLocation()) {
						Log.d("Test", "no location yet");
					}
					Location l=ll.getLocation();
					lm.removeUpdates(ll);
					if(l!=null) {
						GeoLocation gl=new GeoLocation(l.getLatitude(), l.getLongitude());
						Const.twitter.updateStatus(message,gl);
					}
					else {
						Const.twitter.updateStatus(message);
					}
				}
				else {
					Const.twitter.updateStatus(message);
				}
				Log.d("Test", "twitter tweeted");
				status = true;
			} catch (TwitterException e) {
				e.printStackTrace();
			}
		} else if (type == Const.TYPE_PLURK) {
			try {
				Log.d("Test", "plurk add");
				JSONObject ret = Const.plurk.getPc().plurkAdd(message,
						Qualifier.SAYS);
				if (ret.isNull("error_text")) {
					status = true;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		Message m = mHandler.obtainMessage();
		Bundle b = new Bundle();
		b.putInt("type", type);
		b.putBoolean("status", status);
		b.putInt("tID", tID);
		m.setData(b);
		mHandler.sendMessage(m);
	}

}

class LogoutThread extends Thread {
	Handler mHandler;
	boolean status;
	int tID;

	public LogoutThread(Handler mHandler, int tID) {
		this.mHandler = mHandler;
		this.tID = tID;
	}

	@Override
	public void run() {
		status = true;
		Const.facebook = null;
		Const.twitter = null;
		Const.plurk = null;
		Const.myPlurks = null;
		Const.myTweets = null;
		Const.myFacebookStatus=null;
		Const.myFacebookUsers=null;
		Const.myTwitterUsers=null;
		Const.myPlurkUsers=null;
		Const.myPlurkResponses = null;
		Const.myFacebookComments = null;
		Const.myFacebookStatus = null;
		Const.curStatusMessage = null;
		System.gc();
		Message m = mHandler.obtainMessage();
		Bundle b = new Bundle();
		b.putBoolean("status", status);
		b.putInt("tID", tID);
		m.setData(b);
		mHandler.sendMessage(m);
	}

}

class UploadImageThread extends Thread {
	Handler mHandler;
	boolean status;
	int tID;
	byte[] data;
	File file;
	public UploadImageThread(Handler mHandler,byte[] data,File file, int tID) {
		this.mHandler = mHandler;
		this.tID = tID;
		this.data=data;
		this.file=file;
	}

	@Override
	public void run() {
		status = false;
		String url="";
		try {
			Log.d("Test","upload image"+Const.yfrog.getUsername()+Const.yfrog.getPassword());
			if(data!=null) {
				url = Const.yfrog.upload(data);
			}
			else {
				url = Const.yfrog.upload(file);
			}
			if(!url.equals("")) {
				status=true;
				Log.d("Test","upload image success");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		Message m = mHandler.obtainMessage();
		Bundle b = new Bundle();
		b.putBoolean("status", status);
		b.putInt("tID", tID);
		b.putString("url",url);
		m.setData(b);
		mHandler.sendMessage(m);
	}

}
